package cn.ac.sec.liquid.index;

import java.util.List;

import javax.servlet.http.HttpSession;

import cn.ac.sec.liquid.common.model.Oilfield;
import cn.ac.sec.liquid.common.model.User;

import com.jfinal.core.Controller;

/**
 * IndexController
 */
public class IndexController extends Controller {
	
	/**
	 * 注销或登录
	 * session.removeAttribute("login_user"); // 注销操作
	 */
	public void index() {
		HttpSession session = getSession(); // 获取session对象
		session.invalidate(); //使session失效，清空session，不能再使用之前的连接
		render("/login/login.html"); // 不指定绝对路径时，是指/index/index.html
	}
	
	/**
	 * 首页
	 */
	public void homePage() {
		render("/index/index.html");
	}
	public void login() {
		render("/login/login.html");
	}
	/**
	 * 表单登录时，执行的action
	 */
	public void formLogin(){
		HttpSession session = getSession(); //获取session对象		
		User mUser = getModel(User.class); //获取表单数据，创建对象后使用set为对象设定属性,此处只有username和passwd两个有值
		String ckName="rmName";//cookie
		String ckPassword="rmPassword";//cookie
		String userName=getPara("user.username");
	    String userPassword=getPara("user.passwd");
	    String remember=getPara("remember");
	    if(userName==null ||"".equals(userName)){
	    	setAttr("userError", "用户名不能为空");
	    	render("/login/login.html");
	    }else if(userPassword==null ||"".equals(userPassword)){
	    	setAttr("passwordError", "密码不能为空");
	    	render("/login/login.html");
	    }else {
	    	List<User> list = User.dao.find("select * from user where username=?", userName);
	    	if (list.size() > 0) { //用户名存在
				if (userPassword.equals(list.get(0).getPasswd())) {//登录成功
					session.setAttribute("login_user", mUser); //将当前登录用户放入session
					if(remember!=null){//保存密码,存cookie
						setCookie(ckName, userName, 864000);//过期十天
						setCookie(ckPassword, userPassword, 864000);
					}else{
						setCookie(ckName, "", 0);
						setCookie(ckPassword, "", 0);
					}
					render("/index/index.html"); //不指定绝对路径时，是指/index/index.html
				} else {
					setAttr("userError", "用户名或密码不正确");
					render("/login/login.html"); 
				}
			} else {
				setAttr("userError", "用户名不存在");
				render("/login/login.html"); 		
			}
	    }	
	}
	
	
	/**
	 * 显示日历
	 */
	public void calendar() {
		render("/index/calendar.html"); 
	}
	
	public void sidebar(){
		List<Oilfield> list = Oilfield.dao.find("select * from oilfield order by id");
		setAttr("list",list);
		renderJson();
	}
}